// 市场数据管理组合式函数
import type { MarketInstrument, SectorType, ExchangeType, FilterOptions } from '~/types/market'

export const useMarketData = () => {
  // 响应式数据
  const instruments = ref<MarketInstrument[]>([])
  const filteredInstruments = ref<MarketInstrument[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  
  // 筛选条件
  const filters = ref<FilterOptions>({
    sector: 'all',
    exchange: 'all'
  })
  
  // 模拟数据生成
  const generateMockData = (): MarketInstrument[] => {
    const mockInstruments: MarketInstrument[] = [
      {
        id: '1',
        symbol: 'OP',
        name: '双胶纸',
        sector: 'chemical',
        exchange: 'dce',
        currentPrice: 4194.07,
        change: -0.26,
        changePercent: -0.26,
        impliedVol: 11.39,
        volChange: -1.05,
        daysToExpiry: 62,
        contracts: ['2601', '2602'],
        selectedContract: '2601',
        volatilityData: generateVolatilityData(3800, 4600, 10, 16),
        openInterestData: generateOpenInterestData(3800, 4600, -30, 150)
      },
      {
        id: '2',
        symbol: 'SR',
        name: '白糖',
        sector: 'agricultural',
        exchange: 'zce',
        currentPrice: 5448.41,
        change: -0.21,
        changePercent: -0.21,
        impliedVol: 7.67,
        volChange: -0.24,
        daysToExpiry: 48,
        contracts: ['2601', '2603', '2605'],
        selectedContract: '2601',
        volatilityData: generateVolatilityData(5200, 5900, 7, 14),
        openInterestData: generateOpenInterestData(5200, 5900, -5000, 30000)
      },
      {
        id: '3',
        symbol: 'I',
        name: '铁矿石',
        sector: 'ferrous',
        exchange: 'dce',
        currentPrice: 800.5,
        change: -0.08,
        changePercent: -0.08,
        impliedVol: 17.26,
        volChange: 1.32,
        daysToExpiry: 0,
        contracts: ['2511', '2512', '2601', '2605'],
        selectedContract: '2601',
        volatilityData: generateVolatilityData(780, 810, 7, 35),
        openInterestData: generateOpenInterestData(780, 810, -5000, 20000)
      },
      {
        id: '4',
        symbol: 'SC',
        name: '原油',
        sector: 'chemical',
        exchange: 'ine',
        currentPrice: 465.011,
        change: 1.22,
        changePercent: 1.22,
        impliedVol: 30.09,
        volChange: 2.07,
        daysToExpiry: 19,
        contracts: ['2512', '2601'],
        selectedContract: '2601',
        volatilityData: generateVolatilityData(420, 540, 27, 42),
        openInterestData: generateOpenInterestData(420, 540, -1000, 4000)
      },
      {
        id: '5',
        symbol: 'CU',
        name: '沪铜',
        sector: 'metal',
        exchange: 'shfe',
        currentPrice: 87627.4,
        change: 1.88,
        changePercent: 1.88,
        impliedVol: 26.52,
        volChange: 7.84,
        daysToExpiry: 3,
        contracts: ['2511', '2512', '2601', '2602'],
        selectedContract: '2601',
        volatilityData: generateVolatilityData(84000, 94000, 20, 50),
        openInterestData: generateOpenInterestData(84000, 94000, -4000, 8000)
      },
      {
        id: '6',
        symbol: 'UR',
        name: '尿素',
        sector: 'chemical',
        exchange: 'zce',
        currentPrice: 1642.09,
        change: 0.36,
        changePercent: 0.36,
        impliedVol: 16.18,
        volChange: -1.15,
        daysToExpiry: 48,
        contracts: ['2512', '2601', '2602', '2605'],
        selectedContract: '2601',
        volatilityData: generateVolatilityData(1500, 1960, 15, 30),
        openInterestData: generateOpenInterestData(1500, 1960, -3000, 15000)
      },
      {
        id: '7',
        symbol: '510050',
        name: '上证50ETF',
        sector: 'stock-index',
        exchange: 'sse',
        currentPrice: 3.1916,
        change: 0.75,
        changePercent: 0.75,
        impliedVol: 15.42,
        volChange: -0.06,
        daysToExpiry: 33,
        contracts: ['2511', '2512', '2603', '2606'],
        selectedContract: '2603',
        volatilityData: generateVolatilityData(2.85, 3.6, 14, 23),
        openInterestData: generateOpenInterestData(2.85, 3.6, -20000, 120000)
      },
      {
        id: '8',
        symbol: 'JD',
        name: '鸡蛋',
        sector: 'agricultural',
        exchange: 'dce',
        currentPrice: 2873,
        change: 1.13,
        changePercent: 1.13,
        impliedVol: 19.17,
        volChange: 2.60,
        daysToExpiry: 0,
        contracts: ['2511', '2512', '2601', '2602'],
        selectedContract: '2601',
        volatilityData: generateVolatilityData(2850, 2900, 16, 24),
        openInterestData: generateOpenInterestData(2850, 2900, -5000, 20000)
      }
    ]
    
    // 生成更多数据以填满16个卡片
    const additionalInstruments = generateAdditionalInstruments()
    return [...mockInstruments, ...additionalInstruments]
  }
  
  // 生成波动率数据
  const generateVolatilityData = (minStrike: number, maxStrike: number, minVol: number, maxVol: number) => {
    const data = []
    const steps = 8
    const stepSize = (maxStrike - minStrike) / steps
    
    for (let i = 0; i <= steps; i++) {
      const strike = minStrike + i * stepSize
      // 生成U型波动率曲线
      const center = (minStrike + maxStrike) / 2
      const distance = Math.abs(strike - center)
      const maxDistance = (maxStrike - minStrike) / 2
      const vol = minVol + (maxVol - minVol) * (distance / maxDistance)
      
      data.push({
        strike: Math.round(strike),
        impliedVol: Math.round(vol * 100) / 100,
        openInterest: Math.round(Math.random() * 1000),
        date: new Date().toISOString()
      })
    }
    
    return data
  }
  
  // 生成持仓量数据
  const generateOpenInterestData = (minStrike: number, maxStrike: number, minOI: number, maxOI: number) => {
    const data = []
    const steps = 8
    const stepSize = (maxStrike - minStrike) / steps
    
    for (let i = 0; i <= steps; i++) {
      const strike = minStrike + i * stepSize
      const oi = minOI + Math.random() * (maxOI - minOI)
      
      data.push({
        strike: Math.round(strike),
        impliedVol: 0,
        openInterest: Math.round(oi),
        date: new Date().toISOString()
      })
    }
    
    return data
  }
  
  // 生成额外的工具数据
  const generateAdditionalInstruments = (): MarketInstrument[] => {
    const additional = []
    const symbols = ['A', 'SA', 'EB', 'Y', '500ETF', '50ETF', 'CJ', 'RU']
    const names = ['豆一', '纯碱', '苯乙烯', '豆油', '中证500ETF', '科创50ETF', '红枣', '橡胶']
    const sectors: SectorType[] = ['agricultural', 'chemical', 'chemical', 'oil', 'stock-index', 'stock-index', 'agricultural', 'chemical']
    const exchanges: ExchangeType[] = ['dce', 'zce', 'dce', 'dce', 'sse', 'sse', 'zce', 'shfe']
    
    for (let i = 0; i < 8; i++) {
      const basePrice = 1000 + Math.random() * 5000
      const change = (Math.random() - 0.5) * 10
      const vol = 10 + Math.random() * 20
      const volChange = (Math.random() - 0.5) * 5
      
      additional.push({
        id: `${i + 9}`,
        symbol: symbols[i],
        name: names[i],
        sector: sectors[i],
        exchange: exchanges[i],
        currentPrice: basePrice,
        change: change,
        changePercent: change,
        impliedVol: vol,
        volChange: volChange,
        daysToExpiry: Math.floor(Math.random() * 100),
        contracts: ['2601', '2602'],
        selectedContract: '2601',
        volatilityData: generateVolatilityData(basePrice * 0.8, basePrice * 1.2, vol * 0.7, vol * 1.3),
        openInterestData: generateOpenInterestData(basePrice * 0.8, basePrice * 1.2, -5000, 20000)
      })
    }
    
    return additional
  }
  
  // 筛选数据
  const filterInstruments = () => {
    filteredInstruments.value = instruments.value.filter(instrument => {
      const sectorMatch = filters.value.sector === 'all' || instrument.sector === filters.value.sector
      const exchangeMatch = filters.value.exchange === 'all' || instrument.exchange === filters.value.exchange
      return sectorMatch && exchangeMatch
    })
  }
  
  // 更新筛选条件（互斥逻辑）
  const updateFilters = (newFilters: Partial<FilterOptions>) => {
    // 如果选择了板块（非全部），则重置交易所为全部
    if (newFilters.sector && newFilters.sector !== 'all') {
      filters.value = { 
        sector: newFilters.sector, 
        exchange: 'all' 
      }
    }
    // 如果选择了交易所（非全部），则重置板块为全部
    else if (newFilters.exchange && newFilters.exchange !== 'all') {
      filters.value = { 
        sector: 'all', 
        exchange: newFilters.exchange 
      }
    }
    // 如果选择的是"全部"，则更新对应字段
    else {
      filters.value = { ...filters.value, ...newFilters }
    }
    
    filterInstruments()
  }
  
  // 获取数据
  const fetchData = async () => {
    loading.value = true
    error.value = null
    
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 生成模拟数据
      instruments.value = generateMockData()
      filterInstruments()
    } catch (err) {
      error.value = '获取数据失败'
      console.error('Error fetching market data:', err)
    } finally {
      loading.value = false
    }
  }
  
  // 刷新数据
  const refreshData = async () => {
    await fetchData()
  }
  
  // 监听筛选条件变化
  watch(filters, () => {
    filterInstruments()
  }, { deep: true })
  
  // 初始化数据
  if (process.client) {
    onMounted(() => {
      fetchData()
    })
  } else {
    // 服务端直接生成数据
    instruments.value = generateMockData()
    filterInstruments()
  }
  
  return {
    instruments: readonly(instruments),
    filteredInstruments: readonly(filteredInstruments),
    loading: readonly(loading),
    error: readonly(error),
    filters: readonly(filters),
    updateFilters,
    refreshData
  }
}